﻿$(function () {
    'use strict';
    layui.use(['form', 'element', 'notice', 'upload'], function () {
        var form = layui.form,
            element = layui.element,
            uploader = layui.upload,
            notice = Util.notice !== null && Util.notice() !== null
                ? Util.notice() : layui.notice,
            avatarUploadIns = null;
            
        let lodash = _;
        var renderLeftNav = function ($thisElm) {
            //layui在nav切换时清除了layui-this中的伪类after
            //为了实现在当前选项卡中加上右边框费尽周折，必须加上！！
            let $border = $('div.currentnav'),
                loading = layer.load(2, { time: 2000 });
            if (typeof $border !== "undefined") $border.remove();
            $thisElm.after('<div class="currentnav"></div>');
            $("#rightpanel>.layui-card").addClass("layui-hide");
            
            $.wait(300).then(function () {
                layer.close(loading); 
                let $panel = $("div#" + $thisElm.data("tab"));
                if ($panel.length > 0)
                    $panel.removeClass("layui-hide");
            });
            element.render('nav', 'leftnav');
        };
        var initPageComponent = function () {
            renderLeftNav($('.layui-nav-side .layui-this>a'));

            //上传头像图片初始化
            var avtarUrl = $("input[name=FaceImageUrl]").val();
            var avatarinfo = null;
            if (avtarUrl !== "") {
                avatarinfo = lodash.split(avtarUrl, ';', 2);
                $("img#avatar").attr('src', avatarinfo[1]);
            }
            avatarUploadIns = uploader.render({
                elem: '#LAY_avatarUpload'
                , url: '/api/backend/account/uploadavatar'
                , accept: 'images'
                , acceptMime: 'image/*'
                , field: "ImageForm"
                , data: {
                    "Id": $("input[name=Id]").val(),
                    "ImageUrl": $("input[name=FaceImageUrl]").val()
                }
                , before: function (obj) {
                //预读本地文件示例，不支持ie8
                    obj.preview(function (index, file, result) {
                        $("img#avatar").attr('src', result); //图片链接（base64）
                    });
                }
                , done: function (res) {
                    if (res.state && res.state === 200) {
                        notice.success(res.message);
                        $("input[name=FaceImageUrl]").val(res.data);
                    }
                    else notice.error(res.message);
                }
                , error: function () {
                    notice.error("上传图片失败，请联系系统管理");
                }
            });

        };
        element.on('nav(leftnav)', function (data) {
            renderLeftNav($(this));
        });
        initPageComponent();

        $("#LAY_avatarUpload").on("click", function () {
            avatarUploadIns.reload({
                data: {
                    "Id": $("input[name=Id]").val(),
                    "ImageUrl": $("input[name=FaceImageUrl]").val()
                }
            });
        });
        //修改用户显示名称
        $("a#updateUsername").on('click', function () {
            let $this = $(this),
                originName = $this.data("origindata"),
                $inputElm = $this.parent().find("input");
            if ($inputElm.val().toLocaleLowerCase() === originName.toLocaleLowerCase()) {
                notice.error("新修改名称不能与旧名称相同");
                $inputElm.focus();
                $inputElm.addClass("layui-form-danger");
                return false;
            }
            let propName = $inputElm.attr('name');
            let data = {};
            data.Id = $this.data("id");
            if (!data.hasOwnProperty(propName))
                data[propName] = $inputElm.val();
            httpapi.fetchPost('/api/backend/account/edit', data).then(res => {
                if (!httpapi.checkResponse(res))
                    //输入信息校验错误
                    notice.error(res.message);
                else {//Success
                    notice.success(res.message);
                    $this.data('origindata', $inputElm.val());
                    if ($inputElm.hasClass('layui-form-danger'))
                        $inputElm.removeClass('layui-form-danger');
                }
            }).catch(error => notice.error("对不起，出现未知错误，请您联系系统管理员！"));
        });
        $("a#changePassword").on('click', function () {
            Util.OpenMainWindow({
                title: "更换密码",
                type: 2,
                content: "/account/setting/changepwd",
                width: 560,
                height: 390,
                iframeAuto: true
            });
        });
        
    });
});